package com.aglow.bluetoothspeaker.main.ui.activity;

import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.actions.ibluz.manager.BluzManagerData;
import com.aglow.bluetoothspeaker.R;
import com.aglow.bluetoothspeaker.main.base.BaseActivity;
import com.aglow.bluetoothspeaker.main.ui.adapter.ViewPagerAdapter;
import com.aglow.bluetoothspeaker.main.ui.fragment.MusicInfoFragment;
import com.aglow.bluetoothspeaker.main.ui.fragment.MusicListFragment;
import com.aglow.bluetoothspeaker.model.bean.Music;
import com.aglow.bluetoothspeaker.model.cache.MusicCache;
import com.aglow.bluetoothspeaker.model.event.ItemItentEvent;
import com.aglow.bluetoothspeaker.model.event.PlayMusicModeEvent;
import com.aglow.bluetoothspeaker.model.event.VolumeChangedEvent;
import com.aglow.bluetoothspeaker.presenter.lisnter.OnPlayerEventListener;
import com.aglow.bluetoothspeaker.presenter.service.PlayService;
import com.aglow.bluetoothspeaker.utils.BluzManagerUtils;
import com.aglow.bluetoothspeaker.utils.SpManager;
import com.marcinmoskala.arcseekbar.ArcSeekBar;
import com.marcinmoskala.arcseekbar.ProgressListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;


import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: chufeng
 * Email: 392044178@qq.com
 * Date: 2018/9/12 12:15
 */
public class MusicActivity extends BaseActivity {


    @BindView(R.id.seekArc)
    ArcSeekBar seekArc;
    @BindView(R.id.ib_return)
    ImageButton ibReturn;
    @BindView(R.id.music_cover)
    ImageView musicCover;
    @BindView(R.id.btn_music_play)
    ImageButton btnMusicPlay;
    @BindView(R.id.music_control_model)
    ImageButton musicControlModel;
    @BindView(R.id.btn_power_down)
    ImageButton btnPowerDown;
    @BindView(R.id.btn_power_up)
    ImageButton btnPowerUp;
    @BindView(R.id.btn_music_pre)
    ImageButton btnMusicPre;
    @BindView(R.id.btn_music_next)
    ImageButton btnMusicNext;
    @BindView(R.id.view_pager)
    ViewPager viewPager;

    private ObjectAnimator rotation;
    private int playMode = 0; //默认播放模式 0=默认, 1=循环, 2=随机
    private int playState = 0;//默认播放状态 0=停止
    private int progress;
    private long currentPlayTime;
    private PlayService mPlayService;
    private BluzManagerUtils mBluzManagerUtils;
    private boolean updateFinish = false;
    private ProgressDialog loadingDialog;
    private boolean isPlaying;
    private ArrayList<Fragment> fragments;
    private ViewPagerAdapter pagerAdapter;



    @Override
    public int getLayoutId() {
        return R.layout.activity_music1;
    }

    @Override

    public void initData() {

        rotation = ObjectAnimator.ofFloat(musicCover, "Rotation", 0f, 360f);
        rotation.setDuration(5000);
        rotation.setRepeatCount(ObjectAnimator.INFINITE);
        rotation.setRepeatMode(ObjectAnimator.RESTART);
        rotation.setInterpolator(new LinearInterpolator());
        mPlayService = MusicCache.getPlayService();
        mBluzManagerUtils = BluzManagerUtils.getInstance();
        mBluzManagerUtils.setMode(BluzManagerData.FuncMode.A2DP);
        updateFinish = SpManager.getInstance().getMusicListUpdateFinish();


        int volume = SpManager.getInstance().getCurrentVolume();
        int maxVolume = SpManager.getInstance().getMaxVolume();

        seekArc.setMaxProgress(maxVolume);
        Log.i("MusicActivity", "volume = " + volume);
        seekArc.setProgress(volume);

        //添加fragment
        fragments = new ArrayList<>();
        fragments.add(new MusicInfoFragment());
        fragments.add(new MusicListFragment());
        pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(fragments.size());



    }

    @Override
    public void initView() {
        loadingDialog = new ProgressDialog(mContext);
        loadingDialog.setMessage(getString(R.string.loading));

        if (!updateFinish) {
            loadingDialog.setCancelable(false);
            loadingDialog.show();
        } else {
            if (MusicCache.getMusicList().size() > 0) {
                int playingPosition = mPlayService.getPlayingPosition() == -1 ? 0 : mPlayService.getPlayingPosition();
                //TO: BluetoothPlayControlFragment.updateMusicInfo 更新音乐播放信息
                EventBus.getDefault().postSticky(MusicCache.getMusicList().get(playingPosition));
            }
        }
        //TO: BluetoothPlayControlFragment.playStateChanged 更新音乐播放状态

        if (mPlayService.isPlaying()) {
            EventBus.getDefault().postSticky(new MusicStateChangeEvent(true));
        } else {
            EventBus.getDefault().postSticky(new MusicStateChangeEvent(false));
        }

    }

    @Override
    public void onBackClick() {
        finish();
    }



    @Override
    public void addViewListener() {

        seekArc.setOnStopTrackingTouch(new ProgressListener() {
            @Override
            public void invoke(int progress) {
                Log.i("MusicActivity", "progress = " + progress);
                BluzManagerUtils.getInstance().setVolume(progress);
            }
        });

        mPlayService.setOnPlayEventListener(new OnPlayerEventListener() {
            @Override
            public void onChange(Music music) {
                EventBus.getDefault().postSticky(music);
            }

            @Override
            public void onPlayerStart() {
                EventBus.getDefault().postSticky(new MusicStateChangeEvent(true));
            }

            @Override
            public void onPlayerPause() {
                EventBus.getDefault().postSticky(new MusicStateChangeEvent(false));
                Log.i("music","监听器执行了");
            }

            @Override
            public void onPublish(int progress) {

            }

            @Override
            public void onBufferingUpdate(int percent) {

            }

            @Override
            public void onMusicListUpdate() {
                loadingDialog.dismiss();
            }
        });
    }


    @OnClick({R.id.ib_return, R.id.btn_music_play, R.id.music_control_model, R.id.btn_power_down, R.id.btn_power_up, R.id.btn_music_pre, R.id.btn_music_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_return:
                finish();
                break;
            case R.id.btn_music_play:
                if (mPlayService.getPlayingMusic() == null) {
                    mPlayService.play(0);
                } else {
                    mPlayService.playPause();
                }
                break;
            case R.id.btn_music_next:
                     mPlayService.next();
                break;
            case R.id.btn_music_pre:
                    mPlayService.prev();

                break;
            case R.id.music_control_model:
                if (playMode == 0) {//循环模式
                    musicControlModel.setImageResource(R.drawable.buletooth_music_singletunecirculation);
                    playMode = 1;
                    mPlayService.setLoopMode(playMode);
                } else if (playMode == 1) {//随机
                    musicControlModel.setImageResource(R.drawable.buletooth_music_randomplay);
                    playMode = 2;
                    mPlayService.setLoopMode(playMode);

                } else if (playMode == 2) {//默认
                    musicControlModel.setImageResource(R.drawable.buletooth_music_orderplay);
                    playMode = 0;
                    mPlayService.setLoopMode(playMode);
                }
                break;
            case R.id.btn_power_down:
                progress = seekArc.getProgress();
                if (progress >= 0) {
                    progress--;
                    seekArc.setProgress(progress);
                    BluzManagerUtils.getInstance().setVolume(progress);
                }
                break;
            case R.id.btn_power_up:
                progress = seekArc.getProgress();
                if (progress <= 100) {
                    progress++;
                    Log.i("muse", "progress=" + progress);
                    seekArc.setProgress(progress);
                    BluzManagerUtils.getInstance().setVolume(progress);
                }


                break;
        }
    }


    @SuppressWarnings("unused")
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onVolumeChange(VolumeChangedEvent event) {
        int volume = event.getVolume();
        boolean mute = event.isMute();
        seekArc.setProgress(volume);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ItentViewPager(ItemItentEvent itemItentEvent) {
        viewPager.setCurrentItem(0);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void playStateChanged(MusicStateChangeEvent event) {
        isPlaying = event.isPlaying();
        btnMusicPlay.setImageResource(isPlaying ? R.drawable.buletooth_music_suspend : R.drawable.buletooth_music_play);

        if (isPlaying) {
            playAnimation();
        } else {
            stopAnimantion();
        }
    }

    private void playAnimation() {
        rotation.start();
        rotation.setCurrentPlayTime(currentPlayTime);
    }

    private void stopAnimantion() {
        currentPlayTime = rotation.getCurrentPlayTime();
        rotation.cancel();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rotation.cancel();
        rotation = null;


    }


    public class MusicStateChangeEvent {
        private boolean isPlaying;

        public MusicStateChangeEvent(boolean isPlaying) {
            this.isPlaying = isPlaying;
        }

        public boolean isPlaying() {
            return isPlaying;
        }

        public void setPlaying(boolean playing) {
            isPlaying = playing;
        }
    }


}
